﻿
using AnesSystem.Controls;
using AnesSystem.Models;
using AnesSystem.Services;
using AnesSystem.ViewModels;
using AnesSystem.ViewModels.Configuration.DataGrid;
using Common;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using static AnesSystem.ClassHelper;

namespace AnesSystem
{
    public class DataManager : BaseManager<DataManager>
    {

        #region Variables

        private string _hospital = "";

        private string _nameSpace = "";

        private string result = "";

        private string _isInAorP = Constants.ISANES;

        private UdpMsgAnalysis _xmlAnalysisModel = new UdpMsgAnalysis();

        private PatientLinkModel _patientLink;

        private IEnumerable<MenuListModel> _menuList = new List<MenuListModel>();

        private AccountModel _login = new AccountModel();

        private ObservableCollection<AccountModel> _accountList = new ObservableCollection<AccountModel>();

        private Dictionary<string, FrameworkElement> _noPatientLinkExclusiveCtrls;

        private Dictionary<ObjectId, Dictionary<string, FrameworkElement>> _patientLinkCache;

        private ConfigOperationRoomModel _curRoom;

        //code-->configVitalSignsModel
        private Dictionary<string, ConfigVitalSignsModel> _code2signs = new Dictionary<string, ConfigVitalSignsModel>();

        //code-->IconCtrlName
        private Dictionary<string, string> _code2IconName = new Dictionary<string, string>();

        //code-->configEventsModel
        private Dictionary<string, ConfigEventsModel> _code2events = new Dictionary<string, ConfigEventsModel>();

        //name-->configEventsModel
        private Dictionary<string, ConfigEventsModel> _name2events = new Dictionary<string, ConfigEventsModel>();

        //periodTime-->configEventsModelList
        private Dictionary<int, List<ConfigVitalSignsModel>> _periodTime2signs = new Dictionary<int, List<ConfigVitalSignsModel>>();
        private List<string> _classList;

        private FrameworkElement _currentContent;


        #endregion

        #region Constructor

        public DataManager()
        {
            IsNotNeedSaveData = true;
            _curRoom = new ConfigOperationRoomModel();
            _patientLinkCache = new Dictionary<ObjectId, Dictionary<string, FrameworkElement>>();
            Initial();
        }

        #endregion

        #region Properties

        public BaseTableControl AnesRecordCtrl
        {
            get
            {
                if (CurrentControl is BaseAnesRecordCtrl)
                {
                    return CurrentControl as BaseTableControl;
                }
                if (_patientLinkCache.ContainsKey(CurrentPatientLink.Id))
                {
                    string menuName = "";
                    Dictionary<string, FrameworkElement> ctrlDic = _patientLinkCache[CurrentPatientLink.Id];
                    foreach (string item in ctrlDic.Keys)
                    {
                        if (item.Contains("AnesRecordCtrl"))
                        {
                            menuName = item;
                            break;
                        }
                    }
                    return ctrlDic[menuName] as BaseTableControl;
                }
                return null;

            }
        }

        public BaseTableControl PacuRecordCtrl
        {
            get
            {
                if (CurrentControl is BasePacuRecordCtrl)
                {
                    return CurrentControl as BaseTableControl;
                }
                if (_patientLinkCache.ContainsKey(CurrentPatientLink.Id))
                {
                    string menuName = "";
                    Dictionary<string, FrameworkElement> ctrlDic = _patientLinkCache[CurrentPatientLink.Id];
                    foreach (string item in ctrlDic.Keys)
                    {
                        if (item.Contains("PacuRecordCtrl"))
                        {
                            menuName = item;
                            break;
                        }
                    }
                    return ctrlDic[menuName] as BaseTableControl;
                }
                return null;
            }
        }

        /// <summary>
        /// 获取当前医院信息
        /// </summary>
        public Hospital CurrentHospital
        {
            get
            {
                return HospitalConfig.Instance.CurrentHospital;
            }
        }

        /// <summary>
        /// 是否需要保存数据
        /// </summary>
        public bool IsNotNeedSaveData { get; set; }

        public PatientLinkModel CurrentPatientLink
        {
            get
            {
                return _patientLink;
            }

            set
            {
                if (value != null && _patientLink != null)
                {
                    if (!value.Id.ToString().Equals(_patientLink.Id.ToString()))
                    {
                        VitalSignCapture.Instance.StopCapture();
                    }
                }
                _patientLink = value;

                //老版本
                //MainPageCommonViewModel.Instance.PatientLink = _patientLink;

                //新版本
                CommonPageViewModel.Instance.PatientLink = _patientLink;
                if (_patientLink != null)
                {
                    OperationDataPool.Instance.SetCurOer();
                }
            }
        }

        /// <summary>
        /// 获取当前打开的页
        /// </summary>
        public FrameworkElement CurrentControl
        {
            get
            {
                //old
                //return RightContentCtrlViewModel.Instance.CurrentRightContent;

                //new
                return (NavigateManager.Instance.Page._userControl.Content as CommonPageContent)._rightContent.ViewModel.CurrentRightContent;
            }
        }

        public RightContentCtrlViewModel RightContentCtrlViewModel
        {
            get
            {
                //old
                //return RightContentCtrlViewModel.Instance.CurrentRightContent;

                //new
                return (NavigateManager.Instance.Page._userControl.Content as CommonPageContent)._rightContent.ViewModel;
            }
        }

        public TableHeaderCtrl TableHeaderCtrl
        {
            get
            {
                return (NavigateManager.Instance.Page._userControl.Content as CommonPageContent)._tableHeaderCtrl;
            }
        }

        /// <summary>
        /// 非PatientLink专属的页面集合
        /// </summary>
        public Dictionary<string, FrameworkElement> NoPatientLinkExclusiveCtrls
        {
            get
            {
                if (_noPatientLinkExclusiveCtrls == null)
                {
                    _noPatientLinkExclusiveCtrls = new Dictionary<string, FrameworkElement>();
                }
                return _noPatientLinkExclusiveCtrls;
            }

            set
            {
                _noPatientLinkExclusiveCtrls = value;
            }
        }

        public AccountModel Login
        {
            get
            {
                return _login;
            }

            set
            {
                _login = value;
            }
        }

        public IEnumerable<MenuListModel> MenuList
        {
            get
            {
                return _menuList;
            }

            set
            {
                _menuList = value;
            }
        }

        public IEnumerable<AccountModel> AccountList
        {
            get
            {
                return AccountListCtrlViewModel.Instance.AccountList;
            }

        }

        public ConfigOperationRoomModel CurRoom
        {
            get
            {
                return _curRoom;
            }

            set
            {
                _curRoom = value;
            }
        }

        public IEnumerable<ConfigDepartmentsModel> ConfigDepartmentsModelList
        {
            get
            {
                return ConfigDapartmentDataGridViewModel.Instance.ConfigDepartmentsModels;
            }

        }

        public IEnumerable<ConfigDrugMethodsModel> ConfigDrugMethodsModelList
        {
            get
            {
                return ConfigDrugMethodsDataGridViewModel.Instance.ConfigDrugMethodsModel;
            }

        }

        public ObservableCollection<ConfigDrugTypesModel> ConfigDrugTypesModelList
        {
            get
            {
                return ConfigDrugTypesDataGridViewModel.Instance.ConfigDrugTypesModel;
            }

        }

        public ObservableCollection<ConfigDrugGroupTypesModel> ConfigDrugGroupTypesModelList
        {
            get
            {
                return ConfigDrugGroupTypesDataGridViewModel.Instance.ConfigDrugGroupTypesModel;
            }

        }

        public ObservableCollection<AnesRecordTemplateModel> AnesRecordTemplateModelList
        {
            get
            {
                return ConfigTemplateDataGridViewModel.Instance.AnesRecordTemplateModelList;
            }

        }

        public ObservableCollection<ConfigChannelsModel> ConfigChannelsModelList
        {
            get
            {
                return ConfigChannelsDataGridViewModel.Instance.ConfigChannelsModels;
            }

        }

        public ObservableCollection<ConfigContainersModel> ConfigContainersModelList
        {
            get
            {
                return ConfigContainersDataGridViewModel.Instance.ConfigContainersModel;
            }
        }

        public ObservableCollection<ConfigUnitsModel> ConfigUnitsModelList
        {
            get
            {
                return ConfigUnitDataGridViewModel.Instance.ConfigUnitsModel;
            }


        }

        public ObservableCollection<ConfigUnitTypesModel> ConfigUnitTypesModelList
        {
            get
            {
                return ConfigUnitTypesDataGridViewModel.Instance.ConfigUnitTypesModel;
            }
        }

        public ObservableCollection<ConfigVitalSignsModel> ConfigVitalSignsModelList
        {
            get
            {
                return ConfigVitalSignsDataGridViewModel.Instance.ConfigVitalSigns;
            }
        }

        public ObservableCollection<ConfigEventsModel> ConfigEventsModelList
        {
            get
            {
                return ConfigEventDataGridViewModel.Instance.ConfigEventModels;
            }
        }
        public ObservableCollection<ConfigPrescriptionTypesModel> ConfigPrescriptionTypesModelList
        {
            get
            {
                return ConfigPrescriptionTypesDataGridViewModel.Instance.ConfigPrescriptionTypesModel;
            }

        }

        public ObservableCollection<ConfigLiquidTypesModel> ConfigLiquidTypesModelList
        {
            get
            {
                return ConfigLiquidTypesDataGridViewModel.Instance.ConfigLiquidTypesModel;
            }

        }
        public ObservableCollection<ConfigDrugReasonsModel> ConfigDrugReasonsModelList
        {
            get
            {
                return ConfigDrugReasonsDataGridViewModel.Instance.ConfigDrugReasonsModel;
            }

        }

        public ObservableCollection<ConfigEventTypesModel> ConfigEventTypesModelList
        {
            get
            {
                return ConfigEventTypesDataGridViewModel.Instance.ConfigEventTypesModel;
            }

        }

        public ObservableCollection<ConfigDrugsModel> ConfigDrugsModelList
        {
            get
            {
                return ConfigDrugsDataGridViewModel.Instance.ConfigDrugsModel;
            }

        }
        public ObservableCollection<ConfigConsumablesModel> ConfigConsumablesModelList
        {
            get
            {
                return ConfigConsumablesCtrlViewModel.Instance.ConfigConsumablesModel;
            }

        }
        public ObservableCollection<ConfigOperationRoomModel> ConfigOperationRoomModelList
        {
            get
            {
                return ConfigRoomDataGridViewModel.Instance.ConfigOperationRoomModel;
            }

        }


        public Dictionary<string, ConfigVitalSignsModel> Code2signs
        {
            get
            {
                return _code2signs;
            }

            set
            {
                _code2signs = value;
            }
        }

        public List<string> ClassList
        {
            get
            {
                if (_classList == null)
                {
                    _classList = new List<string>();
                    Type[] types = Assembly.GetExecutingAssembly().GetTypes();
                    foreach (var item in types)
                    {
                        if (item.IsClass && item.FullName.Contains("AnesSystem.Controls") &&
                            (item.BaseType != null && (item.BaseType == typeof(UserControl) ||
                                item.BaseType.Equals(typeof(BaseTableControl)) ||
                                item.BaseType.Equals(typeof(CustomCommonTableCtrl)))))
                        {
                            _classList.Add(item.FullName.Replace("AnesSystem.Controls.", ""));
                        }
                    }
                }
                return _classList;
            }
        }

        public PatientDrugsModel PatientDrugsModel { get; internal set; }



        /// <summary>
        /// //已经查看过的手术缓存
        /// </summary>
        public Dictionary<ObjectId, Dictionary<string, FrameworkElement>> PatientLinkCache
        {
            get
            {
                return _patientLinkCache;
            }

            set
            {
                _patientLinkCache = value;
            }
        }

        public string Result
        {
            get
            {
                return result;
            }

            set
            {
                result = value;
            }
        }

        public Dictionary<int, List<ConfigVitalSignsModel>> PeriodTime2signs
        {
            get
            {
                return _periodTime2signs;
            }

            set
            {
                _periodTime2signs = value;
            }
        }

        public Dictionary<string, ConfigEventsModel> Code2events
        {
            get
            {
                return _code2events;
            }

            set
            {
                _code2events = value;
            }
        }

        public Dictionary<string, ConfigEventsModel> Name2events
        {
            get
            {
                return _name2events;
            }

            set
            {
                _name2events = value;
            }
        }

        public UdpMsgAnalysis XmlAnalysisModel
        {
            get
            {
                //if (_xmlAnalysisModel == null) _xmlAnalysisModel = new XmlAnalysisModel();
                return _xmlAnalysisModel;
            }

            set
            {
                _xmlAnalysisModel = value;
            }
        }

        public string IsInAorP
        {
            get
            {
                return _isInAorP;
            }

            set
            {
                _isInAorP = value;
            }
        }

        public Dictionary<string, string> Code2IconName
        {
            get
            {
                return _code2IconName;
            }

            set
            {
                _code2IconName = value;
            }
        }
        #endregion

        #region Event

        #endregion

        #region Private Methods

        private void Initial()
        {
            InitialRoomId();
            InitialMenuList();
            InitialConfigSigns();
            InitialConfigEvents();
            InitialLoginId();
            //MongoDBUtil.Instance.StartTask();
        }

        /// <summary>
        /// 体征字典
        /// </summary>

        private void InitialConfigSigns()
        {
            InitIcon();
            var cvsList = ConfigVitalSignsModelService.Instance.FindAll();
            foreach (var item in cvsList)
            {
                if (Code2IconName.ContainsKey(item.code))
                {
                    item.iconCtrl = Code2IconName[item.code];
                }
                else
                {
                    item.iconCtrl = "CommonCtrl";
                }
                _code2signs.Add(item.code, item);
                int result = item.dataSource;
                if (result < 2 && !("param_null").Equals(item.code))
                {
                    int period = item.capperiod;
                    if (!PeriodTime2signs.ContainsKey(period))
                    {
                        PeriodTime2signs.Add(period, new List<ConfigVitalSignsModel>());
                    }
                    List<ConfigVitalSignsModel> list = PeriodTime2signs[period];
                    list.Add(item);
                }

            }
        }

        private void InitIcon()
        {
            Code2IconName.Clear();
            Code2IconName.Add("param_cvp", "ZXJMYCtrl");
            Code2IconName.Add("param_ibp_s", "YCSSYCtrl");
            Code2IconName.Add("param_ibp_d", "YCSZYCtrl");
            Code2IconName.Add("param_ibp_m", "YCPJYCtrl");
            Code2IconName.Add("param_spo2", "XYBHDCtrl");
            Code2IconName.Add("param_HR", "XLCtrl");
            Code2IconName.Add("param_nibp_d", "WCSZYCtrl");
            Code2IconName.Add("param_nibp_s", "WCSSYCtrl");
            Code2IconName.Add("param_nibp_m", "WCPJYCtrl");
            Code2IconName.Add("param_VT", "VTCtrl");
            Code2IconName.Add("param_T", "TWCtrl");
            Code2IconName.Add("param_QiFuYa", "QFYCtrl");
            Code2IconName.Add("param_anes_PPEAK", "PPEAKCtrl");
            Code2IconName.Add("param_resp_ctrl", "KZHXCtrl");
            Code2IconName.Add("param_ETCO2", "JHETCO2Ctrl");
            Code2IconName.Add("param_I:E", "IECtrl");
            Code2IconName.Add("param_resp", "HXCtrl");
            Code2IconName.Add("param_sub_resp", "FZHXCtrl");
            Code2IconName.Add("param_bis_BIS", "BISCtrl");
            Code2IconName.Add("param_FiO2", "FIO2Ctrl");



        }


        /// <summary>
        /// 事件字典
        /// </summary>
        private void InitialConfigEvents()
        {
            foreach (var item in ConfigEventsModelList)
            {
                try
                {
                    if (!Code2events.ContainsKey(item.Code))
                        Code2events.Add(item.Code, item);
                    if (!Name2events.ContainsKey(item.Name))
                        Name2events.Add(item.Name, item);
                }
                catch (Exception ex)
                {

                }
            }
        }


        private void InitialRoomId()
        {
            if (string.IsNullOrEmpty(ClientAndServerHelper.Instance.LocalXMLContent.RoomId))
            {
                CurRoom.Name = "1";
            }
            else
            {
                CurRoom.Name = ClientAndServerHelper.Instance.LocalXMLContent.RoomId;
            }
        }

        private void InitialLoginId()
        {
            if (string.IsNullOrEmpty(ClientAndServerHelper.Instance.LocalXMLContent.LoginId))
            {
                Login.LoginName = "";
            }
            else
            {
                Login.LoginName = ClientAndServerHelper.Instance.LocalXMLContent.LoginId;
            }
        }

        private void InitialMenuList()
        {
            _menuList = MenuService.Instance.GetAvailableMenuList();
            foreach (var item in _menuList)
            {
                item.PropertyChanged += Item_PropertyChanged;
            }
        }


        /// <summary>
        /// 绑定的字段属性更改并保存都通过这里完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Item_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (sender is AccountModel)
            {
                AccountService.Instance.Update(sender as AccountModel);
            }
            else if (sender is MenuListModel)
            {
                MenuService.Instance.Update(sender as MenuListModel);
            }
        }

        /// <summary>
        /// 填充值到xml
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        /// <param name="tableName"></param>
        /// <param name="doc"></param>
        private void FillValueToXml(string fieldName, string value, string tableName, XmlDocument doc)
        {
            try
            {
                XmlElement root = (XmlElement)doc.GetElementsByTagName("TableName")[0];
                if (root == null)
                {
                    root = doc.CreateElement("TableName");
                    root.SetAttribute("value", tableName);
                    doc.AppendChild(root);
                }

                XmlNode node = doc.GetElementsByTagName(fieldName)[0];
                if (node == null)
                {
                    XmlElement e = doc.CreateElement(fieldName);
                    e.InnerXml = value;
                    root.AppendChild(e);
                }
                else
                {
                    node.InnerText = value;
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }

        #endregion

        #region Public/Protected Methods

        /// <summary>
        /// 获取控件
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public FrameworkElement GetFrameworkElement(string menuName, string Id = "")
        {
            FrameworkElement ctrl = null;
            try
            {
                IsNotNeedSaveData = true;

                string fullName = "AnesSystem.Controls." + menuName;
                Type type = Type.GetType(fullName);
                Object obj = null;

                if (NoPatientLinkExclusiveCtrls.ContainsKey(menuName))
                {
                    ctrl = NoPatientLinkExclusiveCtrls[menuName];
                }
                else
                {
                    if (type != null)
                    {
                        try
                        {
                            obj = Activator.CreateInstance(type);
                        }
                        catch (Exception ex)
                        {
                            Common.LogHelper.Error(this.GetType(), ex);
                        }
                        Common.LogHelper.Fatal(this.GetType(), string.Format("当前选择的菜单是：{0}", type.ToString()));
                    }
                    else
                    {
                        Common.LogHelper.Fatal(this.GetType(), string.Format("当前选择的菜单是：Null"));
                    }
                    //表单类型控件
                    if (obj is BaseTableControl)
                    {
                        if (CurrentPatientLink == null)
                        {
                            Common.LogHelper.Fatal(this.GetType(), string.Format("请选择病人"));
                            return ctrl;
                        }
                        ObjectId objectId = CurrentPatientLink.Id;
                        CurrentPatientLink = PatientLinkService.Instance.GetObjById(objectId.ToString());
                        ctrl = obj as FrameworkElement;
                        FillDataForCustomCommonTableCtrl(ctrl);
                        //缓存暂时取消
                        //if (PatientLinkCache.ContainsKey(objectId))
                        //{
                        //    if (PatientLinkCache[objectId].ContainsKey(menuName))
                        //    {
                        //        ctrl = PatientLinkCache[objectId][menuName];
                        //    }
                        //    else
                        //    {
                        //        ctrl = obj as FrameworkElement;
                        //        FillDataForCustomCommonTableCtrl(ctrl);
                        //        PatientLinkCache[objectId].Add(menuName, ctrl);
                        //    }
                        //}
                        //else
                        //{
                        //    Dictionary<string, FrameworkElement> dic = new Dictionary<string, FrameworkElement>();
                        //    ctrl = obj as FrameworkElement;
                        //    dic.Add(menuName, ctrl);
                        //    FillDataForCustomCommonTableCtrl(ctrl);
                        //    PatientLinkCache.Add(objectId, dic);
                        //}
                    }
                    else
                    {
                        ctrl = obj as FrameworkElement;
                        NoPatientLinkExclusiveCtrls.Add(menuName, ctrl);
                    }
                }
                //功能类型控件
                if (type.BaseType != null && type.BaseType.Equals(typeof(BaseFunctionCtrl)))
                {
                    DataManager.Instance.TableHeaderCtrl.ViewModel.DefaultDisplayModel = 2;
                }
                //功能加打印
                else if (type.BaseType != null && type.BaseType.Equals(typeof(FunctionAndTableCtrl)))
                {
                    DataManager.Instance.TableHeaderCtrl.ViewModel.DefaultDisplayModel = 1;
                }
                else
                {
                    DataManager.Instance.TableHeaderCtrl.ViewModel.DefaultDisplayModel = 2;
                }

                return ctrl;
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error("SysMainWinViewModel", ex);
                return ctrl;
            }
        }

        /// <summary>
        /// 给自定义通用表单填充数据
        /// </summary>
        /// <param name="ctrl"></param>
        public void FillDataForCustomCommonTableCtrl(FrameworkElement ctrl)
        {
            if (ctrl is CustomCommonTableCtrl)
            {
                CustomCommonTableCtrl cCtrl = ctrl as CustomCommonTableCtrl;
                cCtrl.FillValue();
            }
        }

        /// <summary>
        /// 体征
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ConfigVitalSignsModel GetVitalSignsByCode(string code)
        {
            if (!string.IsNullOrEmpty(code))
            {
                if (_code2signs.ContainsKey(code))
                {
                    return _code2signs[code];
                }
                return null;

            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 事件
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ConfigEventsModel GetEventConfigByCode(string code)
        {
            ConfigEventsModel configEvent;
            if (Code2events.ContainsKey(code))
            {
                configEvent = Code2events[code];
            }
            else
            {
                configEvent = createConfigEvent(code);
                // 只在内存加
                //configAll.getEvent().getContent().add(configEvent);
                Code2events.Add(configEvent.Code, configEvent);
                if (!Name2events.ContainsKey(configEvent.Name))
                {
                    Name2events.Add(configEvent.Name, configEvent);
                }

            }
            return configEvent;
        }

        /// <summary>
        /// 根据医生ID转医生姓名
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetAccountNameByID(string id)
        {
            try
            {
                AccountModel model = AccountList.ToList().Find(O => O != null && O.Id != null && O.Id.ToString().Equals(id));
                if (model == null)
                {
                    return "";
                }
                return model.TrueName;
            }
            catch (Exception ex)
            {
                LogHelper.Error(this.GetType(), ex);
                return "";
            }
        }
        public AccountModel GetAccountByID(string id)
        {
            AccountModel model = AccountList.ToList().Find(O => O != null && O.Id != null && O.Id.ToString().Equals(id));
            return model;
        }

        /// <summary>
        /// 创建自定义事件，只存于内存
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ConfigEventsModel createConfigEvent(string code)
        {

            ConfigEventsModel newEvent = new ConfigEventsModel();
            newEvent.Name = code;
            newEvent.Code = code;
            newEvent.Single = true;
            newEvent.EventTypeCode = "其它";
            newEvent.Position = -1;
            newEvent.Deleted = false;

            return newEvent;
        }

        public int GetCurPage(DateTime date)
        {
            if (!date.Equals(new DateTime()))
            {
                DateTime anesStartTime = CurrentPatientLink.Status.AnesRecordStartTime;
                TimeSpan span = date - anesStartTime;
                int minutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                if (minutes % (LocationUtil.SpanMinites * LocationUtil.TotalCol) == 0)
                {
                    return minutes / (LocationUtil.SpanMinites * LocationUtil.TotalCol);
                }
                else
                {
                    return minutes / (LocationUtil.SpanMinites * LocationUtil.TotalCol) + 1;
                }
            }
            else
            {
                return 1;
            }
        }

        public void AddOneEvent(ConfigEventsModel newEvent)
        {
            if (newEvent == null) return;
            if (!Code2events.ContainsKey(newEvent.Code))
            {
                Code2events.Add(newEvent.Code, newEvent);
            }
            if (!Name2events.ContainsKey(newEvent.Name))
            {
                Name2events.Add(newEvent.Name, newEvent);
            }
        }

        /// <summary>
        /// 填充和保存xml表单和控件界面显示的值
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        /// <param name="ctrl"></param>
        /// <returns></returns>
        public bool FillAndSaveXMLTableAndCtrlValue(string fieldName, string value, BaseCustomCtrl ctrl)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(CurrentPatientLink.Tables[ctrl.ClassName].XmlContent);
                FillValueToXml(fieldName, value, ctrl.ClassName, doc);
                CurrentPatientLink.Tables[ctrl.ClassName].XmlContent = doc.InnerXml;
                PatientLinkService.Instance.Update(CurrentPatientLink);
                //UpdViewModel.Instance.SendMsgByIP(ctrl.Name + "|" + ctrl.ClassName + "|" + CurrentPatientLink.Id.ToString());
                return true;
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
                return false;
            }
        }

        /// <summary>
        /// 填充xml表单的值
        /// </summary>
        /// <param name="className"></param>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool FillXMLTableValue(string className, string fieldName, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(CurrentPatientLink.Tables[className].XmlContent);
                FillValueToXml(fieldName, value, className, doc);
                CurrentPatientLink.Tables[className].XmlContent = doc.InnerXml;
                //UpdViewModel.Instance.SendMsgByIP(ctrl.Name + "|" + ctrl.ClassName + "|" + CurrentPatientLink.Id.ToString());
                return true;
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
                return false;
            }
        }

        /// <summary>
        /// 填充和保存xml表单的值
        /// </summary>
        /// <param name="fieldAndValues"></param>
        /// <returns></returns>
        public bool FillAndSaveXMLTableValue(Dictionary<string, object> fieldAndValues)
        {
            try
            {
                if (CurrentControl is CustomCommonTableCtrl)
                {
                    CustomCommonTableCtrl ctrl = CurrentControl as CustomCommonTableCtrl;
                    XmlDocument doc = new XmlDocument();
                    if (ctrl.TableName == null || !CurrentPatientLink.Tables.ContainsKey(ctrl.TableName)) return false;
                    doc.LoadXml(CurrentPatientLink.Tables[ctrl.TableName].XmlContent);
                    foreach (var item in fieldAndValues)
                    {
                        if (item.Value == null) continue;
                        FillValueToXml(item.Key, item.Value.ToString(), ctrl.TableName, doc);
                    }
                    CurrentPatientLink.Tables[ctrl.TableName].XmlContent = doc.InnerXml;
                    PatientLinkService.Instance.Update(CurrentPatientLink);
                    //UpdViewModel.Instance.SendMsgByIP(ctrl.Name + "|" + ctrl.TableName + "|" + CurrentPatientLink.Id.ToString());
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
                return false;
            }
        }

        /// <summary>
        /// 填充控件界面显示的值
        /// </summary>
        /// <param name="fieldAndValues"></param>
        /// <returns></returns>
        public bool FillCtrlValue(Dictionary<string, object> fieldAndValues)
        {
            try
            {
                if (CurrentControl is CustomCommonTableCtrl)
                {

                    CustomCommonTableCtrl ctrl = CurrentControl as CustomCommonTableCtrl;
                    IsNotNeedSaveData = true;
                    foreach (var item in fieldAndValues)
                    {
                        if (item.Value == null) continue;
                        if (!ctrl.BaseCustomCtrls.ContainsKey(item.Key)) continue;
                        ctrl.BaseCustomCtrls[item.Key].Value = item.Value;
                    }
                    IsNotNeedSaveData = false;
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
                return false;
            }
        }

        /// <summary>
        /// 获取当前表单字段的值
        /// </summary>
        /// <param name="p">手术</param>
        /// <param name="tableName">某张表单</param>
        /// <param name="fields">需要获取值的字段</param>
        /// <returns></returns>
        public List<string> GetXMLTableValue(PatientLinkModel p, string tableName, params string[] fields)
        {
            List<string> list = new List<string>();
            XmlDocument doc = new XmlDocument();
            if (p != null && p.Tables.ContainsKey(tableName))
            {
                doc.LoadXml(p.Tables[tableName].XmlContent);
                foreach (var item in fields)
                {
                    if (doc.GetElementsByTagName(item) != null && doc.GetElementsByTagName(item).Count > 0)
                    {
                        list.Add(doc.GetElementsByTagName(item)[0].InnerText);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取当前表单字段的值
        /// </summary>
        /// <param name="p">手术</param>
        /// <param name="tableName">某张表单</param>
        /// <param name="field">需要获取值的字段集合</param>
        /// <returns></returns>
        public List<string> GetCurPatientXMLTableValue(string tableName, params string[] fields)
        {
            List<string> list = new List<string>();
            PatientLinkModel p = CurrentPatientLink;
            XmlDocument doc = new XmlDocument();
            if (p != null && p.Tables.ContainsKey(tableName))
            {
                doc.LoadXml(p.Tables[tableName].XmlContent);
                foreach (var item in fields)
                {
                    if (doc.GetElementsByTagName(item) != null && doc.GetElementsByTagName(item).Count > 0)
                    {
                        list.Add(doc.GetElementsByTagName(item)[0].InnerText);
                    }

                }
            }
            return list;
        }

        /// <summary>
        /// 获取当前表单字段的值
        /// </summary>
        /// <param name="p">手术</param>
        /// <param name="tableName">某张表单</param>
        /// <param name="field">需要获取值的字段集合</param>
        /// <returns></returns>
        public Dictionary<string, string> GetCurPatientXMLTableValue_Dic(string tableName, params string[] fields)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            PatientLinkModel p = CurrentPatientLink;
            XmlDocument doc = new XmlDocument();
            if (p != null && p.Tables.ContainsKey(tableName))
            {
                doc.LoadXml(p.Tables[tableName].XmlContent);
                foreach (var item in fields)
                {
                    if (doc.GetElementsByTagName(item) != null && doc.GetElementsByTagName(item).Count > 0)
                    {
                        dic.Add(item, doc.GetElementsByTagName(item)[0].InnerText);
                    }

                }
            }
            return dic;
        }

        /// <summary>
        /// 获取当前表单字段的值
        /// </summary>
        /// <param name="p">手术</param>
        /// <param name="tableName">某张表单</param>
        /// <param name="field">需要获取值的字段</param>
        /// <returns></returns>
        public string GetCurPatientXMLTableValue(string tableName, string field)
        {
            PatientLinkModel p = CurrentPatientLink;
            XmlDocument doc = new XmlDocument();
            if (p != null && p.Tables.ContainsKey(tableName))
            {
                doc.LoadXml(p.Tables[tableName].XmlContent);

                if (doc.GetElementsByTagName(field) != null && doc.GetElementsByTagName(field).Count > 0)
                {
                    return doc.GetElementsByTagName(field)[0].InnerText;
                }
            }
            return "";
        }


        /// <summary>
        /// 删除单个病人的缓存数据
        /// </summary>
        /// <param name="id"></param>
        public void RemoveCurPatientLink(ObjectId id)
        {
            if (PatientLinkCache.ContainsKey(id))
            {
                PatientLinkCache.Remove(id);
            }
            CurrentPatientLink = null;
        }

        public void RefCurrentPatientLink()
        {
            //   CurrentPatientLink = PatientLinkService.Instance.GetObjById(CurrentPatientLink.Id.ToString());

        }
        public void ReomveVitalSignByCode(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return;
            }
            int index = -1;
            List<ConfigVitalSignsModel> vitals = new List<ConfigVitalSignsModel>();
            if (IsInAorP.Equals(Constants.ISANES))
            {
                vitals = CurrentPatientLink.VitalSignShow.VitalSign;
            }
            if (IsInAorP.Equals(Constants.ISPACU))
            {
                vitals = CurrentPatientLink.VitalSignShow.PacuVitalSign;
            }
            if (IsInAorP.Equals(Constants.ISLABOR))
            {
                vitals = CurrentPatientLink.VitalSignShow.LaborVitalSign;
            }
            for (int i = 0; i < vitals.Count; i++)
            {
                if (code.Equals(vitals[i].code))
                {
                    index = i;
                }
            }
            if (index != -1)
            {
                if (IsInAorP.Equals(Constants.ISANES))
                {
                    CurrentPatientLink.VitalSignShow.VitalSign.RemoveAt(index);
                }
                if (IsInAorP.Equals(Constants.ISPACU))
                {
                    CurrentPatientLink.VitalSignShow.PacuVitalSign.RemoveAt(index);
                }
                if (IsInAorP.Equals(Constants.ISLABOR))
                {
                    CurrentPatientLink.VitalSignShow.LaborVitalSign.RemoveAt(index);
                }

            }
            PatientLinkService.Instance.AddUpdate(CurrentPatientLink);
        }

        #endregion

        #region EventHandlers



        #endregion

    }
}
